package com.fengchao.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 发邮件工具
 * Created by wangnian on 2016/7/7.
 */
@Component
public class MailTools {


    @Autowired
    Environment env;

    private static Logger logger = LoggerFactory.getLogger(MailTools.class);


    public boolean SendMail(String title, String text, Exception ex) {
        new Thread(()-> {
                try {
                    String sendUserName = "message@letswarm.com";
                    String sendPassword = "Fengqi2016";
                    Properties properties = new Properties();
                    properties.setProperty("mail.smtp.auth", "true");//服务器需要认证
                    properties.setProperty("mail.transport.protocol", "smtp");//声明发送邮件使用的端口
                    Session session = Session.getInstance(properties);
                    session.setDebug(false);//同意在当前线程的控制台打印与服务器对话信息
                    Message message = new MimeMessage(session);//构建发送的信息
                    message.setText(text + stackMessage(ex));//信息内容
                    message.setSubject(env.getProperty("spring.profiles.active") + "环境异常," + title);
                    message.setFrom(new InternetAddress("message@letswarm.com"));//发件人
                    Transport transport = session.getTransport();
                    transport.connect("smtp.exmail.qq.com", 25, sendUserName, sendPassword);//连接发件人使用发件的服务器
                    transport.sendMessage(message, new Address[]{new InternetAddress("wangn@letswarm.com")});//接受邮件
                    transport.close();
                } catch (Exception ex1) {
                    logger.warn("发送邮件消息失败=exception:{}", ex1);
                }

        }).start();
        return true;
    }

    //获得堆栈内容
    public static String stackMessage(Exception ex) {
        if (ex == null) {
            return "";
        }
        StringBuffer strBuf = new StringBuffer(ex.getMessage() + "\n");
        StackTraceElement[] errors = ex.getStackTrace();
        for (StackTraceElement e : errors) {
            strBuf = strBuf.append(e.toString() + "\n");
        }
        return strBuf.toString();
    }
}